//
//  KKPhotosManager+Private.m
//  KKPhotosKitDemo
//
//  Created by liaozhenming on 2017/8/31.
//  Copyright © 2017年 liaozhenming. All rights reserved.
//

#import "KKPhotosManager+Private.h"
#import "AppDelegate.h"
#import <objc/runtime.h>

@implementation KKPhotosManager (Private)

- (BOOL)kk_authStatusWithCamera:(KKPhotosManagerEventBlockHandle)eventBlock {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeVideo];
    switch (authStatus) {
        case AVAuthorizationStatusNotDetermined:
        {
            [AVCaptureDevice requestAccessForMediaType: AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    if (eventBlock) {
                        eventBlock();
                    }
                }
            }];
            
            return false;
        }
            break;
        case AVAuthorizationStatusRestricted:
        case AVAuthorizationStatusDenied:
        {
            [self kk_showErrorMessage: @"请在设备的\"设置-隐私-相机\"中允许访问相机权限"];
            return false;
        }
            break;
        default:
            break;
    }
    
    return true;
}

- (BOOL)kk_authStatusWithLibrary:(KKPhotosManagerEventBlockHandle)eventBlock {
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    switch (authStatus) {
        case PHAuthorizationStatusNotDetermined:
        {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                
                if (status == PHAuthorizationStatusAuthorized) {
                    if (eventBlock) {
                        eventBlock();
                    }
                }
            }];
            
            return false;
        }
            break;
        case PHAuthorizationStatusRestricted:
        case PHAuthorizationStatusDenied:
        {
            [self kk_showErrorMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限"];
            return false;
        }
            break;
        default:
            break;
    }
    return true;
}

- (void)kk_showErrorMessage:(NSString*)mesage {
    NSLog(@"alert..message = %@",mesage);
}

- (UIViewController*)kk_rootViewController {
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    return appDelegate.window.rootViewController;
}


//  获取缩率图
+ (void)kk_getThumbImageForAsset:(PHAsset*)asset targetSize:(CGSize)size resultHandle:(KKPhotosManagerImageResultBlockHandle)resultHandle {
    
    KKPhotosManager_ImageRequestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    [[PHCachingImageManager defaultManager] requestImageForAsset: asset targetSize: size contentMode:PHImageContentModeAspectFill options: KKPhotosManager_ImageRequestOptions resultHandler:^(UIImage *result, NSDictionary *info) {
        
        BOOL downloadFinined = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey] && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue];
        if (downloadFinined && resultHandle) {
            resultHandle(result);
        }
    }];
}

//  获取图片Data组
+ (void)kk_getImageDatasForAssets:(NSArray*)assets original:(BOOL)original resultHandle:(KKPhotosManagerImageDatasResultBlockHandle)resultHandle {
    KKPhotosManager_ImageRequestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    KKPhotosManager_ImageRequestOptions.synchronous = NO;
    
    NSMutableArray *arr_imageResult = [NSMutableArray array];
    
    __block NSInteger assetCount = assets.count;
    
    for (PHAsset *asset in assets) {
        
        CGFloat defaultWidth = 180.0;
        CGFloat defaultHeight = 240.0;
        
        CGSize size = CGSizeMake(defaultWidth, defaultHeight);
        if (original) {
            size = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
        }
        else {
            CGFloat widthScale = asset.pixelWidth / defaultWidth;
            CGFloat heightScale = asset.pixelHeight / defaultHeight;
            CGFloat scale = MAX(widthScale, heightScale);
            size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
        }
        
//        [[PHCachingImageManager defaultManager] requestImageForAsset: asset targetSize: size contentMode:PHImageContentModeAspectFill options: KKPhotosManager_ImageRequestOptions resultHandler:^(UIImage *result, NSDictionary *info) {
//
//            BOOL downloadFinined = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey] && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue];
//            if (downloadFinined && resultHandle) {
//                [arr_imageResult addObject: result];
//
//                NSData *png_imageData = UIImagePNGRepresentation(result);
//                NSLog(@"png_imageData = %@", @(png_imageData.length));
//
//                NSData *jpg_imageData = UIImageJPEGRepresentation(result, 1.0);
//                NSLog(@"jpg_imageData = %@", @(jpg_imageData.length));
//            }
//        }];
        
        [[PHCachingImageManager defaultManager] requestImageDataForAsset: asset options:KKPhotosManager_ImageRequestOptions resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            [arr_imageResult addObject: imageData];
            assetCount--;
            
            //  当数据全部获取完，调用block函数，将数据传递出去
            if (assetCount == 0) {
                if (resultHandle) {
                    resultHandle(arr_imageResult);
                }
            }
        }];
    }
}

//  获取图片Image组
+ (void)kk_getImagesForAssets:(NSArray*)assets original:(BOOL)original resultHandle:(KKPhotosManagerImagesResultBlockHandle)resultHandle {
    
    KKPhotosManager_ImageRequestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    KKPhotosManager_ImageRequestOptions.synchronous = NO;
    
    NSMutableArray *arr_imageResult = [NSMutableArray array];
    
    __block NSInteger assetCount = assets.count;
    
    for (PHAsset *asset in assets) {
        
        CGFloat defaultWidth = 180.0;
        CGFloat defaultHeight = 240.0;
        
        CGSize size = CGSizeMake(defaultWidth, defaultHeight);
        if (original) {
            size = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
        }
        else {
            CGFloat widthScale = asset.pixelWidth / defaultWidth;
            CGFloat heightScale = asset.pixelHeight / defaultHeight;
            CGFloat scale = MAX(widthScale, heightScale);
            size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
        }
        
        [[PHCachingImageManager defaultManager] requestImageForAsset: asset targetSize: size contentMode:PHImageContentModeAspectFill options: KKPhotosManager_ImageRequestOptions resultHandler:^(UIImage *result, NSDictionary *info) {

            BOOL downloadFinined = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey] && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue];
            if (downloadFinined && resultHandle) {
                [arr_imageResult addObject: result];
                
                assetCount--;
                
                //  当数据全部获取完，调用block函数，将数据传递出去
                if (assetCount == 0) {
                    if (resultHandle) {
                        resultHandle(arr_imageResult);
                    }
                }
            }
        }];
    }
}

//  获取主题色彩
+ (UIColor*)kk_getMainColor {
    return [UIColor colorWithRed:18.0/255.0 green:150.0/255.0 blue:219.0/255.0 alpha:1.0];
}

@end


@implementation _KKPhotosGroupItem
- (instancetype)initWithAssetCollection:(PHAssetCollection *)assetCollection withItemCounts:(NSInteger)counts {
    self = [super init];
    if (self) {
        _kk_assetCollection = assetCollection;
        _kk_count = counts;
        PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
        _kk_firstItem = [assets firstObject];
    }
    return self;
}
@end


@implementation _KKPhotosItem
@end

@implementation _KKPhotosDataManger

+ (instancetype)manager {
    static _KKPhotosDataManger *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [_KKPhotosDataManger new];
    });
    return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _arr_photoItems = [NSMutableArray array];
    }
    return self;
}

- (BOOL)kk_isEqualItem:(PHAsset*)asset {
    
    for (PHAsset *tmpItem in _arr_photoItems) {
        if ([tmpItem.localIdentifier isEqualToString: asset.localIdentifier]) {
            return true;
        }
    }
    return false;
}

- (void)kk_addItem:(PHAsset*)asset {
    if (![self kk_isEqualItem: asset]) {
        [_arr_photoItems addObject: asset];
    }
}

- (void)kk_removeItem:(PHAsset*)asset {
    if ([self kk_isEqualItem: asset]) {
        [_arr_photoItems removeObject: asset];
    }
}
@end

@implementation PHAsset(KKPhotosManager)

const void *PHAsset_KKPhotosManager_ThumbImage = &PHAsset_KKPhotosManager_ThumbImage;
@dynamic kk_thumbImage;
- (void)setKk_thumbImage:(UIImage *)kk_thumbImage {
    objc_setAssociatedObject(self, PHAsset_KKPhotosManager_ThumbImage, kk_thumbImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIImage*)kk_thumbImage {
    return objc_getAssociatedObject(self, PHAsset_KKPhotosManager_ThumbImage);
}

@end
